<?php
/* MyMeeting is an online meeting management software.
 * Copyright (C) 2009 Government Of Malaysia
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * @author: Abdullah Zainul Abidin, Nuhaa All Bakry
 *          Eavay Javay Barnad, Sarogini Muniyandi, Teow Jit Huan
 *
 */

class ItemsController extends AppController {

    /**
     * Define $name
     *
     */
    var $name = 'Items';
    /**
     * Define $helpers
     *
     */
    var $helpers = array('Html', 'Form','Comment','Text','Javascript','Ajax','DatePicker');
    /**
     * Define $uses
     *
     */
    var $uses = array('Item','Group','Meeting','User');

    var $paginate = array('order'=>array('Item.name'=>'asc'));

    var $components = array('RequestHandler');

    /**
     * Describe index
     *
     * @param $committee
     * @return null
     */
    function index($committee) {
        $this->Committee->unbindModel(array('hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Userstatus','Groupstatus','Wfmodel','Todo')),false );
        $this->Committee->unbindModel(array('hasAndBelongsToMany'=>array('User')) );
        
        // get the search terms
        $cursearch_name ='';
        $cursearch_shortname ='';
        if(!empty($this->data['Search']['name']) && $this->data['Search']['name']!='' 
            && !empty($this->data['Search']['short_name']) && $this->data['Search']['short_name']!=''
        ) {
            $cursearch_name = $this->data['Search']['name'];
            $cursearch_shortname=$this->data['Search']['short_name'];
        }elseif(!empty($this->data['Search']['name']) && $this->data['Search']['name']!='') {
            $cursearch_name = $this->data['Search']['name'];
        }elseif(!empty($this->data['Search']['short_name']) && $this->data['Search']['short_name']!='') {
            $cursearch_shortname=$this->data['Search']['short_name'];
        }
        $this->set('cursearch_name',$cursearch_name);
        $this->set('cursearch_shortname',$cursearch_shortname);

        // construct queries
        $cond[0]="Item.committee_id=".$this->dcommittee['Committee']['id'];
        $cond[]="Item.deleted=0";
        if(isset($cursearch_name) && $cursearch_name!='') {
            $cond[]="Item.name like '%".$cursearch_name."%'";
        }
        if(isset($cursearch_shortname) && $cursearch_shortname!='') {
            $cond[]="Item.short_name like '%".$cursearch_shortname."%'";
        }
        $items=$this->paginate('Item',$cond);
        if(!empty($items)){
            $items=$this->fixupauth($items,'Item',$this->permission);
        }
        $this->set('items', $items);
        $this->set('committee',$committee);
    }

    /**
     * Describe view
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function view($committee, $id = null) {
        $this->Item->Committee->unbindModel(array('hasAndBelongsToMany'=>array('User'),'hasMany'=>array('Announcement','Item','Group','Meeting','Decision','Userstatus','Groupstatus','Wfmodel','Todo')),false );
        $this->User->unbindModel(array('hasAndBelongsToMany'=>array('Committee','Meeting','Decision','Group'),'hasMany'=>array('Announcement','Meetingtodo','Userstatus','Groupstatus')),false );
        $this->Meeting->unbindModel(array('hasAndBelongsToMany'=>array('User','Attendance'),'hasMany'=>array('Decision','Notification','Todo')),false );
        $this->Meeting->Behaviors->detach('Comment');
        $this->Meeting->Behaviors->detach('MultiFile');
        
        if (!$id) {
            $this->Session->setFlash(__('Invalid Project.', true));
            $this->redirect(array('action'=>'index'));
        }

        $item=$this->Item->read(null,$id);
        if($item['Item']['committee_id']!=$this->dcommittee['Committee']['id']){
            $this->notpermit();
        }
        $permit=$this->itemPermission($item,array('View'));
        if(empty($permit['View'])){
            $this->notpermit();
        }
        $this->set('item', $item);
        
        //find previous permitted item
        $item2=$item;
        do{
            $not=0;
            $prev=$this->Item->find('first',array(
                'conditions'=>array(
                    'Item.committee_id'=>$this->dcommittee['Committee']['id'],
                    'Item.deleted=0',
                    'Item.name<\''.$item2['Item']['name'].'\'',
                ),
                'fields'=>array('id','name'),
                'order'=>array('Item.name'=>'desc'),
            ));
            if(!empty($prev)){
                $permit_prev=$this->itemPermission($prev,array('View'));
                if(empty($permit_prev['View'])){
                    $item2=$prev;
                    $prev=null;
                    $not=1;
                }
            }
        }while($not==1);
        //find next permitted item
        $item2=$item;
        do{
            $not=0;
            $next=$this->Item->find('first',array(
                'conditions'=>array(
                    'Item.committee_id'=>$this->dcommittee['Committee']['id'],
                    'Item.deleted=0',
                    'Item.name>\''.$item2['Item']['name'].'\'',
                ),
                'fields'=>array('id','name'),
                'order'=>array('Item.name'=>'asc'),
            ));
            if(!empty($next)){
                $permit_next=$this->itemPermission($next,array('View'));
                if(empty($permit_next['View'])){
                    $item2=$next;
                    $next=null;
                    $not=1;
                }
            }
        }while($not==1);
        if($prev){
            $this->set('prev',$prev);
        }
        if($next){
            $this->set('next',$next);
        }
       
        // for search dropdowns
        $groups = $this->Group->find('list',array('conditions'=>array('Group.committee_id'=>$this->dcommittee['Committee']['id']),'order'=>'Group.name ASC'));
        // get all users under this committee
        $users_tmp = $this->User->getUsersPerCommittee($this->dcommittee['Committee']['id']);
        //$users_tmp = $this->User->UsersGroup->find('all',array('conditions'=>array('UsersGroup.group_id'=>array_keys($groups))));
        $users_ids = array_unique(Set::extract($users_tmp, '{n}.Membership.user_id'));
        $users = $this->User->find('list',array('conditions'=>array('User.id'=>$users_ids),'order'=>'User.name ASC'));

        $meetings_tmp = $this->Meeting->find('all',array('conditions'=>array('Meeting.committee_id'=>$this->dcommittee['Committee']['id'],'Meeting.parent_id'=>'0'),'order'=>' Meeting.meeting_num ASC'));
        $meetings_child = $this->Meeting->find('all',array('conditions'=>"Meeting.committee_id='".$this->dcommittee['Committee']['id']."' AND Meeting.parent_id!='0'"));

        foreach ($meetings_tmp as $meet) { 
            $meetings[$meet['Meeting']['id']] = $meet['Meeting']['meeting_num'].' - '.$meet['Meeting']['meeting_title']; 

            //$meetings = $this->_getChild($meet['Meeting']['id'],$meetings_child);
            foreach ($meetings_child as $child) {
                if ($meet['Meeting']['id'] == $child['Meeting']['parent_id']) {
                    $meetings[$child['Meeting']['id']] = "    -- ".$child['Meeting']['meeting_num'].' - '.$child['Meeting']['meeting_title'];
                }
            }
        }
        $this->set(compact('groups','users','meetings'));

        // find decisions to display
        if (!empty($this->data['Search']['meeting']) || !empty($this->data['Search']['group']) || !empty($this->data['Search']['user'])) {
            // for preselected values

            if (isset($this->data['Search']['user']) && $this->data['Search']['user']!='') { 
                $this->set('cursearch_user',$this->data['Search']['user']);
            } 
            if (isset($this->data['Search']['group']) && $this->data['Search']['group']!='') {
                $this->set('cursearch_group',$this->data['Search']['group']);
            } 
            if (isset($this->data['Search']['meeting']) && $this->data['Search']['meeting']!='') {
                $this->set('cursearch_meeting',$this->data['Search']['meeting']);
            }
            // then do the search 
            $decision = $this->Item->Decision->search($this->data['Search']);
        } else { 
            $decision=$this->Item->Decision->find('all',array(
                'conditions'=>array(
                    'Decision.item_id'=>$id,
                    'not'=>array('Decision.id'=>$this->Committee->deletedDecisionId())
                ),
                'order'=>array(
                    'Decision.meeting_id asc',
                    'Decision.ordering asc',
                ),
                'contain'=>array(
                'User.id',
                'User.name',
                'Group.id',
                'Group.name',
                'Groupstatus.group_id',
                'Userstatus.user_id',
                'Meeting.id',
                'Meeting.meeting_num'
                )
            )); 
        }
        $secretariat=array();
        $permiss=array();
        foreach($decision as $i=>$d){
            //deleted the non-implementor status
            $d=$this->Meeting->Decision->unset_nonImpstatus($d);
            //deleted information(decisions which don't have implementor)
            if((empty($d['User'])) && (empty($d['Group']))){
                unset ($decision[$i]);
            }
            //is current user the secrectariat for each decision's meeting
            $secretariat[$d['Decision']['meeting_id']] =$this->Meeting->Attendance->isSecretariat($d['Decision']['meeting_id'],$this->Auth->user('id'));
            if($this->Auth->user('superuser')==0 && $secretariat[$d['Decision']['meeting_id']]==0){
                $permiss[$d['Decision']['id']]=$this->decisionPermission($d);
            }
        }
        $this->set('secretariat',$secretariat);
        $this->set('decisions',$decision);
        $arr=$this->Item->Decision->Check($decision,$this->Auth->user('id'));
        $this->set('A',$arr[0]);
        $this->set('N',$arr[1]);
        $this->set('allow',$arr[2]);
        $this->set('noupdated',$arr[3]);
        $this->set('permission',$this->permission);
        $this->set('permiss',$permiss);
    }
    /**
     * Describe _getChild
     *
     * @param $parent_id
     * @param $children_array
     * @param $return
     * @return null
     */
    /*
    function _getChild($parent_id,&$children_array,&$return=array()) {
        echo "<pre>".print_r($children_array,true)."</pre>";echo '<b>'.count($children_array).'</b>';
        $children = $children_array;
        if (!count($children)) {
            echo "<pre>".print_r($return,true)."</pre>**************";
            return $return;
        }
        else {
            foreach ($children_array as $key=>$child) {
                $child_id = $child['Meeting']['id'];
                if ($parent_id == $child['Meeting']['parent_id']) {
                    $return[$child_id] = " -- ".$child['Meeting']['meeting_num'].' - '.$child['Meeting']['meeting_title'];
                    unset($children[$key]);
                    echo '<br>1';
                } else {
                    unset($children[$key]);echo '<br>2';
                }
                //echo "<pre>".print_r($children,true)."</pre>===================";
                //echo "<br> -- ".$child['Meeting']['meeting_num'].' - '.$child['Meeting']['meeting_title'];;
                echo "<pre>".print_r($return,true)."</pre>===============";
                $this->_getChild($child_id,$children,$return);
            }
        }
    }*/

    /**
     * Describe add
     *
     * @param $committee
     * @return null
     */
    function add($committee) {    
        if (!empty($this->data)) {
            $this->Item->committee_id = $this->dcommittee['Committee']['id']; //for unique validation
            $this->Item->create();
            if ($this->Item->save($this->data)) {
                $this->Session->setFlash(__('The Item has been saved', true));
                $this->redirect(array('committee'=> $this->dcommittee['Committee']['short_name'],'action'=>'index'));
            } else {
                $this->Session->setFlash(__('The Item could not be saved. Please, try again.', true));
            }
        }
    }

    /**
     * Describe ajax_dialog
     *
     * @param $committee
     * @return null
     */
    function ajax_form($committee) {
        if($this->RequestHandler->isAjax()){
            Configure::write('debug', 0); // dont want debug in ajax returned html
            $this->layout='popup';
            $dcommittee=$this->Item->Committee->findByShortName($committee);
            $this->set('dcommittee',$dcommittee);
            if (!empty($this->data)) {
                $this->set('formname',$this->data['name']);
                $this->set('formshort_name',$this->data['short_name']);
                $this->set('formdescription',$this->data['description']);
                $this->Item->create();
                if ($this->Item->save($this->data)) {
                    $this->Session->setFlash(__('The Item has been saved', true));
                    $this->set('saved',true);
                } else {
                    $this->Session->setFlash(__('The Item could not be saved. Please, try again.', true));
                    $this->set('saved',false);
                }
            }
            $committees=$this->Item->Committee->registeredCommitteeList($this->Auth->user('id'));
            $this->set(compact('committees'));
            $this->set('returnpage',$this->referer(null,true));
            $this->render('ajax_form');
        }
        else{
        }
    }

    /**
     * Describe add_dialog
     *
     * @param $committee
     * @return null
     */
    function add_dialog($committee) {
        $this->layout='popup';
        $dcommittee=$this->Item->Committee->findByShortName($committee);
        $this->set('dcommittee',$dcommittee);
        $committees=$this->Item->Committee->registeredCommitteeList($this->Auth->user('id'));
        $this->set(compact('committees'));
        $this->set('returnpage',$this->referer(null,true));
    }

    /**
     * Describe edit
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function edit($committee = null, $id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid Item', true));
            $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'index'));
        }
        if (!empty($this->data)) {
            $this->Item->committee_id = $this->dcommittee['Committee']['id']; //for unique validation
            $this->Item->id = $id;
            if ($this->Item->save($this->data)) {
                $this->Session->setFlash(__('The Item has been saved', true));
                $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'index'));
            } else {
                $this->Session->setFlash(__('The Item could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Item->read(null, $id);
            if($this->Auth->user('superuser')==0){
                $permit=$this->itemPermission($this->data,array('Edit'));
                if(empty($permit['Edit'])){
                    $this->notpermit();
                }
            }
            $this->set('item',$this->data);
        }
    }

    /**
     * Describe delete
     *
     * @param $committee
     * @param $id
     * @return null
     */
    function delete($committee, $id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for Item', true));
            $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'index'));
        }
        $this->Item->delete($id);
        $this->Session->setFlash(__('Item deleted', true));
        $this->redirect(array('committee'=>$this->dcommittee['Committee']['short_name'],'action'=>'index'));
    }

        }
?>
